package auto.test.util;

import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;


//下载断言工具类
public class DownloadUtil {
		
	

	
	public static String getdownloadconfig(String key) {
		GetConfigPath get=new GetConfigPath();
		 ProUtil pro=new ProUtil(get.GetconfigPath());
		 String value= pro.GetPro(key);
		 return value;
	}
	
	 static String downloadsPath=getdownloadconfig("downloadsPath");
		
	 
	 //设置浏览器的下载路径
		public static  WebDriver  setDownloadsPath() {
			
	    	HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
	        chromePrefs.put("download.default_directory", downloadsPath);
	        ChromeOptions options = new ChromeOptions();
	        options.setExperimentalOption("prefs", chromePrefs);
	        DesiredCapabilities caps = new DesiredCapabilities();
	        caps.setCapability(ChromeOptions.CAPABILITY, options);
	        WebDriver driver = new ChromeDriver(caps);
	        return driver;
	     
	    }

		//监听所下载的文件名
		public static String getDownloadedDocumentName(String filepath, String filename)
	    {	
	    	String downloadedFileName = null;
	    	boolean valid = true;
	    	boolean found = false;

	    	//default timeout in seconds
	    	long timeOut = 30; 
	    	try 
	    	{					
	    		Path downloadFolderPath = Paths.get(filepath);
	    		WatchService watchService = FileSystems.getDefault().newWatchService();
	    		downloadFolderPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
	    		long startTime = System.currentTimeMillis();
	    		do 
	    		{
	    			WatchKey watchKey;
	    			watchKey = watchService.poll(timeOut,TimeUnit.SECONDS);
	    			long currentTime = (System.currentTimeMillis()-startTime)/1000;
	    			if(currentTime>timeOut)
	    			{
	    				System.out.println("Download operation timed out.. Expected file was not downloaded");
	    				return downloadedFileName;
	    			}
	    			
	    			for (WatchEvent<?> event: watchKey.pollEvents())
	    			{
	    				WatchEvent.Kind<?> kind = event.kind(); 
	    				if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) 
	    				{
	    					String fileName = event.context().toString();
	    					System.out.println("New File Created:" + fileName);
	    					if(fileName.endsWith(filename))
	    					{
	    						downloadedFileName = fileName;
	    						System.out.println("Downloaded file found with extension " + filename + ". File name is " + fileName);
	    						Thread.sleep(500);
	    						found = true;
	    						break;
	    					}
	    				}
	    			}
	    			if(found)
	    			{
	    				return downloadedFileName;
	    			}
	    			else
	    			{
	    				currentTime = (System.currentTimeMillis()-startTime)/1000;
	    				if(currentTime>timeOut)
	    				{
	    					System.out.println("Failed to download expected file");
	    					return downloadedFileName;
	    				}
	    				valid = watchKey.reset();
	    			}
	    		} while (valid);
	    	} 
	    	
	    	catch (InterruptedException e) 
	    	{
	    		System.out.println("Interrupted error - " + e.getMessage());
	    		e.printStackTrace();
	    	}
	    	catch (NullPointerException e) 
	    	{
	    		System.out.println("Download operation timed out.. Expected file was not downloaded");
	    	}
	    	catch (Exception e)
	    	{
	    		System.out.println("Error occured - " + e.getMessage());
	    		e.printStackTrace();
	    	}
	    	return downloadedFileName;
	}
		
		//确认文件下载是否完成
		public static Boolean isFileDownloaded_Ext(String filepath, String filename) {
	    	boolean flag=false;
	        File dir = new File(filepath);
	        File[] files = dir.listFiles();
	        if (files == null || files.length == 0) {
	            flag = false;
	        }
	        
	        for (int i = 0; i <files.length; i++) {
	        	if(files[i].getName().contains(filename)) {
	        		flag=true;
	        	}
	        }
	        return flag;
		}
		
		

		
	public static void main(String[] args) {
		System.out.println(downloadsPath);

		String fileName = getDownloadedDocumentName(downloadsPath,".zip");
		System.out.println(fileName);
		
		System.out.println(isFileDownloaded_Ext(downloadsPath,fileName));

	}
	
	
}
